package top.oylan.manager.controller.admin;

import com.alibaba.fastjson.JSONObject;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jms.core.JmsMessagingTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import top.oylan.manager.entity.*;
import top.oylan.manager.service.CategoryService;
import top.oylan.manager.service.ProductService;
import top.oylan.manager.service.SectionService;
import top.oylan.manager.tools.*;
import top.oylan.manager.tools.enums.Types;

import javax.annotation.Resource;
import java.util.Date;
import java.util.HashMap;
import java.util.List;

/**
 * Created by A on 2019/2/12.
 * 课程专用
 */
@RequestMapping(value = "/admin/course")
@Controller
public class AdminCourseController {

    @Resource
    ProductService productService;

    @Resource
    CategoryService categoryService;

    @Autowired
    JmsMessagingTemplate jmsMessagingTemplate;

    @Resource
    FileUploader fileUploader;

    @RequestMapping(value = {"","/","/list"})
    public String index(
            @RequestParam(value = "page",defaultValue = "1")Integer page,
            ModelMap modelMap
    ){
        Pager pager = new Pager();
        pager.setCurrentPage(page);
        Product condition = new Product();
        condition.setType((byte)1);
        pager.setCondition(condition);
        List<Course> list = productService.selectCourseByPager(pager);
        pager.setList(list);
        modelMap.addAttribute("pager",pager);
        return "admin/course/list";
    }

    /**
     * 前往添加
     */
    @RequestMapping(value = "/add",method = RequestMethod.GET)
    public String add(ModelMap modelMap){
        getCategory(modelMap);
        return "admin/course/add";
    }


    /**
     * 前往编辑
     */
    @RequestMapping(value = "/edit",method = RequestMethod.GET)
    public String edit(ModelMap modelMap, @RequestParam ("id")Integer id){
        getCategory(modelMap);
        modelMap.addAttribute("course",productService.selectProductById(id));
        return "admin/course/edit";
    }

    /**
     * 读取分类
     * @param modelMap
     */
    private void getCategory(ModelMap modelMap) {
        List<Category> categories = categoryService.selectCategoriesForProduct(Types.COURSE);
        modelMap.addAttribute("categories",categories);
    }

    /**
     * 添加/编辑 保存
     */
    @RequestMapping("/save")
    @ResponseBody
    public Result save(@RequestBody Product course){

        Result result = new Result();
        result.setCode((byte) 0);
        result.setMessage("保存失败");
        if(course.getId() == 0){
           // 添加
           Subject subject = SecurityUtils.getSubject();
           User user = (User) subject.getPrincipal();
           course.setCreateTime(new Date());
           course.setAuthorId(user.getId().shortValue());
           productService.addProduct(course);
           result.setMessage("保存成功");
           result.setCode((byte)1);
        } else{
           // 编辑
           productService.updateProduct(course);
           result.setMessage("保存成功");
           result.setCode((byte)1);
        }
        return result;
    }

    @RequestMapping("/delete")
    public Result delete(@RequestParam Integer id){
        Result result = new Result();
        int del = productService.delete(id);
        if(del>0){
            result.setCode((byte) 1);
        }else{
            result.setCode((byte) 0);
            result.setMessage("删除睡失败");
        }
        return result;
    }

    /**
     * 状态更新
     * @param id
     * @param state
     * @return
     */
    @RequestMapping("/state")
    public Result state(
            @RequestParam Integer id,
            @RequestParam (value = "state",defaultValue = "1",required = false)int state
            ){
        Product product = new Product();
        product.setId(id);
        product.setStatus((byte)state);
        Result result = new Result((byte) 0,"操作失败");
        if(productService.updateProduct(product) > 0){
            result.setCode((byte) 1);
        }
        return result;
    }


    @Resource
    SectionService sectionService;

    @RequestMapping(value = "/sections")
    public String sections(@RequestParam int productId,ModelMap modelMap){
        modelMap.addAttribute("productId",productId);
        Section section = new Section();
        section.setParentId(0);
        section.setProductId(productId);
        List<Section> list = sectionService.selectSectionsByCondition(section);
        modelMap.addAttribute("list",list);
        return "admin/course/sections";
    }

    @RequestMapping(value = "/section/add")
    public String addSection(@RequestParam int productId,ModelMap modelMap){
        modelMap.addAttribute("productId",productId);
        return "admin/course/addSection";
    }

    @RequestMapping(value = "/section/edit",method = RequestMethod.GET)
    public String editSection(ModelMap modelMap,@RequestParam int id){

        Section section = sectionService.findSectionById(id);
        Section condition = new Section();
        condition.setParentId(id);
        condition.setProductId(section.getProductId());
        List<Section> videos = sectionService.selectSectionsByCondition(condition);
        modelMap.addAttribute("videos",videos);
        modelMap.addAttribute("section",section);
        return "admin/course/editSection";
    }

    /**
     * 章节编辑
     * @param jsonObject
     * @return
     */
    @RequestMapping(value = "/section/update",method = RequestMethod.POST)
    @ResponseBody
    public Result updateSection(@RequestBody JSONObject jsonObject){

        Result result = new Result();

        Section section = new Section();
        section.setTitle(jsonObject.getString("title"));
        section.setDescription(jsonObject.getString("description"));
        section.setStatus(jsonObject.getByte("status"));

        sectionService.update(section);
        jmsMessagingTemplate.convertAndSend("queue.update_section_video",jsonObject.toJSONString());
        result.setCode((byte) 1);

        return result;
    }

    /**
     * 章节添加
     * @param jsonObject
     * @return
     */
    @RequestMapping("/section/save")
    @ResponseBody
    public Result sectionSave(@RequestBody JSONObject jsonObject){

        Result result = new Result();
        int id =  sectionService.saveSectionFromJSON(jsonObject);
        if(id >0){
           sectionService.saveVideos(jsonObject,id);
           result.setCode((byte) 1);
        }
        HashMap<String, Object> map = new HashMap<>();
        map.put("productId",jsonObject.getIntValue("productId"));
        result.setData(map);
        return result;
    }

    @RequestMapping(value = "/upload",method = RequestMethod.POST)
    @ResponseBody
    public JSONObject upload(@RequestParam("file") MultipartFile file){
        JSONObject object = new JSONObject();
        Result res = fileUploader.upload(file, Directory.ART);
        if(res.getCode() == 1){
            object.put("status",1);
            object.put("path",res.getData().get("path").toString());
        }else{
            object.put("status",0);
        }
        return object;
    }


    @RequestMapping(value = "/file/remove",method = RequestMethod.GET)
    public Result unlink(@RequestParam(value = "path")String path){

        Result result = new Result((byte) 1,"成功");
        fileUploader.removeFile(SystemConstants.UPLOAD_ROOT_PATH+path);
        return result;
    }
}
